/**
 * Created by hao.cheng on 2017/4/15.
 */
import React from "react";
import {Button, Form, Icon, Modal, Popconfirm, Select, Switch} from "antd";
import request, {get} from "@/axios/tools";
import {connect} from "react-redux";
import {FoodForm} from "@/components/form/foodForm";
import TableContainer from "../tables/TableContainer";

const PLACEHOLDER_IMG = require('@/asset/placeholder_sm.jpg');
const Option = Select.Option;
const DEFAULT_SIZE = 10;


class FoodMenu extends React.Component {
    // 构造
    constructor(props) {
        super(props);
        // 初始状态
        this.state = {
            count: 0,
            currentPage: 1,
            pageSize: DEFAULT_SIZE,
            data: [],
            foodMenu: [],
            formVisible: false,
            previewVisible: false,
            previewImage: {},
            // 当前选中菜品
            currentFood: {},
            picPre: '',
            foodStatus: '',
            orderBy: {},
            upKey: null,
            downKey: null
        };
        this._requestMenuList = this._requestMenuList.bind(this);
        this._handleSelect = this._handleSelect.bind(this);
        this.rowsData = this._getRowData();
        this.menuId = 0;
        this.columns = [{
            title: '编号',
            dataIndex: 'id',
            width: 60,
            render: text => <a>{text}</a>,
        }, {
            title: '名称',
            dataIndex: 'name',
        },
            {
                title: '菜品类型',
                dataIndex: 'foodTypeList',
                render: (text, record) => {
                    let foodType = [];
                    text.forEach((item) => {
                        foodType.push(item.name);
                    })
                    return (foodType.join(', '));
                }
            },
            {
                title: '价格(￥)',
                dataIndex: 'price',
                width: 100,
                render: text => text
            }, {
                title: '优惠价(￥)',
                dataIndex: 'reducedPrice',
                width: 100,
                render: text => text
            },
            {
                title: '分数',
                dataIndex: 'score',
                width: 100,
            },
            {
                title: '图片',
                dataIndex: 'images',
                width: 200,
                render: (value, record) => {
                    const {picPre} = this.state;
                    let imageUrl = PLACEHOLDER_IMG;
                    if (value.length) {
                        const data = value[0];
                        imageUrl = picPre + '/' + data.local;
                    }
                    return (<div style={{width: '100%'}}><img src={imageUrl} alt="test" width="50%"/></div>);
                }
            },
            {
                title: '菜品状态',
                dataIndex: 'status',
                width: 100,
                render: (value, record) => {
                    let statusMap = {
                        'ENABLE': ['上架', ''],
                        'SELL_OUT': ['售罄', '#ff3d1c'],
                        'DISABLE': ['下架', '#b3b3b3']
                    }
                    return (<div style={{color: statusMap[value][1]}}>{statusMap[value][0]}</div>);

                }
            },
            {
                title: '是否参与打折',
                dataIndex: 'allowDiscount',
                width: 100,
                render: (value, record) => {
                    return <Switch checked={value} checkedChildren="是" unCheckedChildren="否"/>

                }
            },
            {
                title: '是否隐藏',
                dataIndex: 'hide',
                width: 100,
                render: (value, record) => {
                    return <Switch checked={value} checkedChildren="是" unCheckedChildren="否"/>

                }
            },
            {
                title: '操作',
                key: 'action',
                // fixed: 'right',
                width: 160,
                render: (text, record) => (
                    <div>
                        <Button onClick={() => this.handleEdit(record)}>编辑</Button>
                        <span className="ant-divider"></span>
                        <Popconfirm title="确定删除?" onConfirm={() => this._deleteFood(record.id)}>
                            <Button>删除</Button>
                        </Popconfirm>
                    </div>
                )
            }
        ];
    }

    _getRowData() {

        let obj = {};
        obj.rows = [];
        obj.number = 0;
        obj.getNumber = function () {
            return obj.number;
        }
        obj.getRows = function () {
            return obj.rows;
        }
        obj.addRow = function (rowData) {
            obj.rows.push(rowData);
            obj.number++;
        };
        obj.removeRow = function (rowData) {
            for (let i in obj.rows) {
                if (obj.rows[i].id === rowData.id) {
                    obj.rows[i] = 0;
                    obj.number--;
                }
            }
        };
        obj.rowsToBuffer = () => {
            let {picPre} = this.state;
            let jsonData = new Object();
            let setmeal = {};
            setmeal.id = null;
            setmeal.images = [];
            setmeal.items = obj.rows;
            setmeal.name = null;
            setmeal.price = 0;
            setmeal.reducedPrice = 0;
            setmeal.status = null;
            jsonData.picPre = picPre;
            jsonData.setmeal = setmeal;
            localStorage.setItem("setmealInfo", JSON.stringify(jsonData));
        }
        return obj;
    };


    componentDidMount() {
        const {currentPage, pageSize} = this.state;
        this._requestMenuList();
    }


    _deleteFood = id => {
        request({url: '/food/item/' + id, method: 'delete'}).then(resp => {
            const data = this.state.data.filter(v => v.id !== id);
            this.setState({data});
        });
    };

    _requestMenuList() {
        const {auth: auth = {data: {}}} = this.props;
        if (auth.data.restaurant) {
            get('/restaurant/listMenus/' + auth.data.restaurant).then(data => {
                data.list.map((item, index) => {
                    return item.key = index;
                });
                this.setState({foodMenu: data.list});
            });
        }
    }

    _requestData = (current, pageSize) => {
        this.setState({data: []});
        const {auth} = this.props;
        const {data: data = {}} = auth;
        const restaurantID = parseInt(data.restaurant);
        if (restaurantID) {
            return get('/restaurant/listFood', {
                restaurantID: restaurantID,
                menuID: this.menuId,
                page: current,
                showAll: true,
                pageSize: pageSize,
                status: this.state.foodStatus || '  ',
                orderBy: this.state.orderBy.key || '',
                desc: this.state.orderBy.desc || ''
            }).then(data => {
                let {basePicUrl} = data.extra;
                this.setState({count: data.total, data: data.data, picPre: basePicUrl});
                return data;
            });
        }
    }

    _handleSelect(value) {
        if (this.menuId !== value) {
            this.menuId = value;
            this.setState({currentPage: 1});
            this.tabCon.reset();
        }
    }

    handleSelectStatus = (value) => {
        this.setState({foodStatus: value}, () => {
            this.tabCon.reset();
        });
    }

    handleOrder = (value) => {
        this.setState({orderBy: {
                key: value ? 'PRICE' : '',
                desc: value === 'DESC'
            }}, this.tabCon.reset)
    }

    handleEdit = (record) => {
        // console.log(record)
        this.setState({
            formVisible: true,
            currentFood: Object.assign({}, record)
        })

        this.getFoodById(record.id)
            .then((res) => {
                let currentFood = Object.assign({}, res.data);
                this.setState({currentFood});
                if (this.refs.foodform) {
                    const {setFieldValue} = this.refs.foodform;
                    setFieldValue(currentFood);
                    // console.log(this.refs.foodform)
                }
            })
    }

    handleCancel = () => {
        this.setState({
            formVisible: false
        })
    }

    handlePreview = (item, picPre) => {
        this.setState({
            previewVisible: true,
            previewImage: {
                url: picPre + '/' + item.local,
                name: item.name,
                description: item.description
            }
        })
    }

    handleAfterSubmit = (res) => {
        // this._requestData(1);
        // console.log('submit')
        let {data, currentFood} = this.state;
        this.getFoodById(currentFood.id)
            .then((res) => {
                currentFood = Object.assign({}, res.data);
                data = data.map((item) => {
                    if (item.id === currentFood.id) {
                        currentFood.key = item.key;
                        return currentFood;
                    }
                    return item;
                })
                this.setState({data, formVisible: false, currentFood});
            })
    }

    getFoodById = (id) => {
        return get('/food/item/' + id);
    }

    getImageList = ({images: files}) => {
        let reg = /\.jpg$|\.png$|\.jpeg$|\.gif$/;
        let imageList = [];
        imageList = files.filter((item) => {
            return reg.test(item.local);
        })
        return imageList;
    };


    _postOrderData = (data) => {
        const body = data.map(v => v.id);
        console.log(' _postOrderData    ', body);
        request({url: '/food/itemOrder', method: 'post', body});
    };

    render() {
        const {foodTypeList, formVisible, previewVisible, previewImage, currentFood, picPre} = this.state;
        const rowSelection = {
            onChange: (selectedRowKeys, selectedRows) => {
                // console.log(`selectedRowKeys: ${selectedRowKeys}`, 'selectedRows: ', selectedRows);
                this.setState({selectedRows, selectedRowKeys});
            },
            onSelect: (record, selected, selectedRows) => {
                if (selected) {
                    this.rowsData.addRow(record);
                }
                else {
                    this.rowsData.removeRow(record);
                }
                console.log(this.rowsData.getRows());
            }
        };
        const imageListRender = (record) => {
            const images = this.getImageList(record);
            const {picPre} = this.state;
            const imageList = images.map((item) => {
                return (
                    <div key={item.id} className="food-image-item">
                        <div className="food-image-info">
                            <img key={item.local} src={picPre + "/" + item.local}/>
                        </div>
                        <div className="food-image-actions">
                            <Icon type="eye-o" onClick={() => {
                                this.handlePreview(item, picPre);
                            }}/>
                        </div>
                    </div>
                )
            });
            return (
                images.length ?
                    <div className="food-image-list">
                        {imageList}
                    </div> : null
            );
        }
        return (
            <div className="content-container">
                <Select placeholder={'选择类型'} style={{width: 130}} onChange={this._handleSelect} allowClear>
                    {this.state.foodMenu.map((item, index) => <Option value={item.id + ''}
                                                                      key={item.id}> {item.name}</Option>)}
                </Select>
                <Select placeholder={'选择状态'} style={{width: 130, marginLeft: 10}} onChange={this.handleSelectStatus}
                        allowClear>
                    <Option value="ENABLE">上架中</Option>
                    <Option value="SELL_OUT">售罄</Option>
                    <Option value="DISABLE">下架</Option>
                </Select>
                <Select placeholder={'选择排序'} style={{width: 140, marginLeft: 10}} onChange={this.handleOrder}
                        allowClear>
                    <Option value="DESC">价格从高到低</Option>
                    <Option value="ASC">价格从低到高</Option>
                </Select>
                <Button style={{width: 120, marginLeft: 10}} type="primary"
                        disabled={this.rowsData.getNumber() === 0} onClick={() => {
                    const {router} = this.props;
                    this.rowsData.rowsToBuffer();
                    router.push('/app/setmeal/SelectFoodList');
                }}>添加套餐</Button>
                <div className="space-bar"></div>
                <TableContainer columns={this.columns}
                                canDragSort={true}
                                callBack={t => this.tabCon = t}
                                expandedRowRender={imageListRender}
                                scroll={{x: 1200}}
                                rowSelection={rowSelection}
                                showSizeChanger={true}
                                dragSortCallBack={this._postOrderData}
                                requestData={this._requestData}/>
                <Modal title="菜品编辑" visible={formVisible} footer={null} onCancel={this.handleCancel}>
                    <FoodForm ref="foodform" {...this.props} handleAfterSubmit={this.handleAfterSubmit}
                              currentFood={currentFood} picPre={picPre} showUpload={true}/>

                </Modal>
                <Modal visible={previewVisible} footer={null} onCancel={() => {
                    this.setState({previewVisible: false})
                }}>
                    <div className="image-info">
                        <h3>{previewImage.name ? previewImage.name : ''}</h3>
                        <p>{previewImage.description ? <span>描述：{previewImage.description}</span> : ''}</p>
                    </div>
                    <img alt="example" style={{width: '100%'}} src={previewImage.url}/>
                </Modal>
            </div>
        );
    }
}

const mapStateToProps = state => {
    const {auth = {data: {}}} = state.httpData;
    return {auth};
};

const WrapperFoodMenu = Form.create()(FoodMenu);
export default connect(mapStateToProps)(WrapperFoodMenu);
